import sys
import random
from math import exp,sqrt
from getopt import getopt
from time import clock

def dot(x,y):
	s = 0.0
	for i in x:
		s += x[i]*y.get(i,0)
	return s

def processSVMlight(f,g,m,v):
    maximum=0
    ss=0.0
    c=0
    if v is None:
      for line in f:
        n=line.find('#')
        line=line[0:n].strip()
        if not line: continue
        s=line.split()
        vector=eval('{'+', '.join(s[1:])+'}')
        l=sqrt(dot(vector,vector))
        ss+=l
        c+=1
        if(l>maximum):
            l=maximum
      z=l if m=='max' else ss/c
      print z
    else:
      z=v
    f.seek(0)
    for line in f:
        n=line.find('#')
        line=line[0:n].strip()
        if not line: continue
        s=line.split()
        vector=eval('{'+', '.join(s[1:])+'}')
        g.write("%s " % s[0])
        keys=vector.keys();
        keys.sort()
        for k in keys:
            if vector[k]!=0:
                g.write("%d:%g " % (k,vector[k]/z))
        g.write("\n")
    f.close()
    g.close()

if __name__=='__main__':
    options={
            '-n':'avg',
            '-o':'.norm'
            }
    optlist,args=getopt(sys.argv[1:], 'n:o:v:')
    options.update(dict(optlist))
    if (len(args)==0):
        print 'Missing input file'
        sys.exit(1)
    if '-v' in options:
        val=float(options['-v'])
    else:
        val=None
    f=open(args[0])
    g=open(args[0]+options['-o'],'w')
    processSVMlight(f,g,options['-n'],val)
